package org.editor.servlet;

import com.google.gson.Gson;
import org.editor.util.FileUploadUtil;
import org.editor.vo.Editor;
import org.editor.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author zqx
 * @Date 2023-12-12
 */
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.当前上传的图片
        Part part = req.getPart("attach");

        // 获取图片上传的物理路径
        String path = req.getServletContext().getRealPath("/images");

        // 4.使用上传工具类来实现文件的上传
        FileUploadUtil fuu = new FileUploadUtil();
        // 设置允许上传文件的大小和类型 - 1MB
        fuu.setMaxSize(1 * 1024 * 1024);
        fuu.setAllowFileExt("jpg,png,jpeg");
        String filename = fuu.upload(part, path);

        // 5.响应
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Editor editor = new Editor();
        editor.setAlt(filename);
        editor.setUrl("http://localhost:8080/images/" + filename);
        ResponseData responseData = new ResponseData();
        responseData.setErrno(0);
        responseData.setData(editor);
        out.println(new Gson().toJson(responseData));
        out.flush();
        out.close();
    }
}
